﻿using GodSharp.Opc.Da;

namespace PPSMS.Commons
{

    public static class Extension
    {
        /// <summary>
        /// 将object转换为指定的类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">object对象</param>
        /// <param name="DataHandler">处理数据的方法</param>
        /// <returns></returns>
        public static T ToValue<T>(this object obj, Func<object, T> DataHandler)
        {
            return DataHandler(obj);
        }
        /// <summary>
        /// 读取OPC数据
        /// </summary>
        /// <param name="itemName">OPC标记名称</param>
        /// <returns>数据/10 转换为double</returns>

        public static double ReadOPCValue(string itemName, bool isPLC = false)
        {
            try
            {
                if (isPLC)
                {
                    return Program.OpcDaClient.ReadNode("default", itemName).Value.ToValue(o => Convert.ToDouble(o.ToString()));
                }
                else
                {
                    return Program.OpcDaClient.ReadNode("default", itemName).Value.ToValue(o => (int)o / 10.0);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("未找到OPC数据");
                return 10.0;
            }
        }
    }
}
